package com.tsfyun.scm.gateway.filter;

import cn.hutool.core.util.IdUtil;
import com.tsfyun.scm.gateway.constant.TraceConstant;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;


@Slf4j
public class RequestFilter implements GlobalFilter, Ordered {

	private AntPathMatcher pathMatcher = new AntPathMatcher();

	private static List<String> noPrint = new ArrayList<String>(){{
		add("/scm/taskNotice/count");
	}};

	@Override
	public int getOrder() {
		return -800;
	}

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		String traceId = IdUtil.fastSimpleUUID();
		MDC.put(TraceConstant.LOG_TRACE_ID, traceId);
		//构建head
		String path = exchange.getRequest().getPath().value();
		ServerHttpRequest.Builder builder = exchange.getRequest().mutate()
				.header(TraceConstant.HTTP_HEADER_TRACE_ID, traceId);
		ServerHttpRequest traceHead = builder.build();
		Boolean isPrint = noPrint.stream().filter(url->pathMatcher.match(url,path)).count() <= 0;
		if(isPrint) {
			log.info("request url = " + exchange.getRequest().getURI() + ", traceId = " + traceId);
		}
		ServerWebExchange build = exchange.mutate().request(traceHead).build();
        return chain.filter(build);

		
	}

	 

}
